package com.hcc.gateway.app.dubbo;

import com.hcc.gateway.common.domain.DubboReq;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;

import java.util.Collections;

/**
 * dubbo泛化调用工具
 *
 * @author shengjun.hu
 * @date 2021/12/30
 */
public class DubboGenericClient {

    /**
     * 泛化调用dubbo接口
     * @param req
     * @return
     */
    public static Object invoke(DubboReq req) {
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        ApplicationConfig application = new ApplicationConfig();
        application.setName(req.getApplicationName());
        referenceConfig.setApplication(application);

        referenceConfig.setRegistry(new RegistryConfig(req.getRegCenterUrl()));
        referenceConfig.setVersion(req.getVersion());
        referenceConfig.setGroup(req.getGroup());

        referenceConfig.setInterface(req.getInterfaceName());
        referenceConfig.setGeneric("true");

        MethodConfig methodConfig = new MethodConfig();
        methodConfig.setName(req.getMethodName());
        methodConfig.setTimeout(req.getTimeout());
        methodConfig.setRetries(req.getRetries());
        referenceConfig.setMethods(Collections.singletonList(methodConfig));

        // 获取泛化服务
        GenericService genericService = referenceConfig.get();

        return genericService.$invoke(req.getMethodName(), req.getParamType(), req.getParam());
    }

}
